package com.suray.wcs.service.pojo.rgv.rgv.protocol.message;

import com.suray.wcs.service.pojo.Rgv;
import com.suray.basic.wcs.utils.typedef.Byte;
import com.suray.basic.wcs.utils.typedef.Word;
import com.suray.wcs.service.pojo.rgv.rgv.protocol.base.RgvRecMessage;
import com.suray.wcs.service.pojo.rgv.rgv.protocol.util.RgvMessageType;

import java.io.IOException;
import java.util.Arrays;

public class RgvFileRecMessage extends RgvRecMessage {

    private final int REC_OK = 0x06;
    private final int REC_ERROR = 0x15;
    private final int REC_REPEAT = 0x7;

    public RgvFileRecMessage(Rgv rgv) {
        super(rgv, "文件发送接收");

        baseDatas.add(new Word("firstFrame", "报文头帧：02 fd"));
        baseDatas.add(new Byte("Deviceid", "小车对应设备号"));
        baseDatas.add(new Byte("life", "心跳、指令、任务共用，res收到后原数据返回"));
        baseDatas.add(new Byte("报文类型", "0. 心跳 1. 整体任务 2. 指令报文  3 调试指令模式  4文件传输模式"));
        baseDatas.add(new Byte("result", "ack:0x06  收到数据包    nak:0x15  未收到或受到的数据包错误    0x07:接受重复"));
        baseDatas.add(new Word("dataNum", "记录接收到的数据包的序号"));
        baseDatas.add(new Word("报文长度", "整条报文的长度"));
        baseDatas.add(new Word("校验位", "CRC（循环冗余校验；低位在前，高位在后），采用crc16_modbus"));
        baseDatas.add(new Word("尾帧", "0x3FC"));
    }

    public int getResult() {
        return getValue("result");
    }

    public int getMessageLength() {
        return getValue("报文长度");
    }

    @Override
    public boolean checkMessage(byte[] recData, RgvMessageType rgvMessageType, Integer sendLife) throws IOException {
        boolean result = super.checkMessage(recData, rgvMessageType, sendLife);

        int messageLength = getMessageLength();
        if (recData.length != messageLength) {
            throw new RuntimeException("解析的报文长度与接收的实际长度不一致:" + Arrays.toString(recData));
        }

        if (result) {
            analyzeMessage();
        }

        return result;
    }

    private void analyzeMessage() {
        int result = getResult();
        if (result == REC_OK || result == REC_REPEAT) {

        } else if (result == REC_ERROR) {
            throw new RuntimeException(getRgv().getRgvName() + "地图接收错误");
        }
    }

    @Override
    public Integer getMessageLife() {
        return getValue("life");
    }

    @Override
    public Integer getMessageType() {
        return getValue("报文类型");
    }
}
